class TokenObserver < ActiveRecord::Observer
  
  def after_create(token)
    token.place.arcs.find(:all, :conditions => {:from_is_place => true}).each do |arc|
      begin
        arc.transition.modtokens << Modtoken.create(:token => token)
        arc.transition.save!
      rescue Exception => e
        raise "Modtoken could not be created for transition #{arc.transition.id}."
      end
    end

    true
  end

  def after_update(token)
    token.place.arcs.find(:all, :conditions => {:from_is_place => true}).each do |arc|
      begin
        token.combinations.destroy_all
        if (arc.transition.modtokens.select{|modtoken| modtoken.token == token}.size == 0)
          arc.transition.modtokens << Modtoken.create(:token => token)
          arc.transition.save!
        end
      rescue Exception => ex
        raise "Updating modtokens for transition #{arc.transition.id} failed."	
      end
    end

    true
  end

  def before_destroy(token)
    cleanup(token)
    true
  end
  
  #deletes modtokens and combinations where token is involved
  def cleanup(token)
    token.modtokens.destroy_all
    token.combinations.destroy_all
  end
end
